<?php

namespace Kollway\CodeGenerator\Utils;

use DB;

class DBUtils
{
    // 数据库所有表名
    protected static $all_tables = [];

    // 所有表名和字段名(不重复)
    protected static $all_table_and_fields = [];

    // 保存表的字段、注释, 查询过的不再查询
    protected static $all_table_info = [];

    /**
     * 获取表的所有字段的 字段名、注释
     * @param $table
     * @return mixed
     */
    public static function getTableInfo($table)
    {
        $prefix = DB::getTablePrefix();

        if (!array_key_exists($table, static::$all_table_info)) {
            $table_info = DB::select('SHOW FULL COLUMNS FROM ' . $prefix . $table);

            $temp = [];
            foreach ($table_info as $item) {
                if (is_object($item)) {
                    $temp[] = [
                        'field' => $item->Field,
                        'comment' => $item->Comment,
                    ];
                } else {
                    $temp[] = [
                        'field' => $item['Field'],
                        'comment' => $item['Comment'],
                    ];
                }
            }

            static::$all_table_info[$table] = $temp;
        }

        return static::$all_table_info[$table];
    }

    /**
     * 获取一个表的所有字段名
     * @param string $table 表名
     * @return array
     */
    public static function getAllTableFields($table)
    {
        if (!array_key_exists($table, static::$all_table_info)) {
            static::$all_table_info[$table] = static::getTableInfo($table);
        }

        return array_column(static::$all_table_info[$table], 'field');
    }

    /**
     * 获取数据库所有表名
     * @return array
     */
    public static function getAllTables()
    {
        if (empty(static::$all_tables)) {
            $db = \DB::getDatabaseName();
            $tables = \DB::select("show tables");

            $temp = [];
            foreach ($tables as $table) {
                if (is_object($table)) {
                    $temp[] = $table->{'Tables_in_' . $db};
                } else {
                    $temp[] = $table['Tables_in_' . $db];
                }
            }

            static::$all_tables = $temp;
        }

        return static::$all_tables;
    }

    /**
     * 获取所有表名和字段名集合
     * @return array
     */
    public static function getAllTablesAndFields()
    {
        if (empty(static::$all_table_and_fields)) {
            $tables = static::getAllTables();

            $fields = [];
            foreach ($tables as $table) {
                $fields = array_merge($fields, static::getAllTableFields(substr($table, 3)));
            }

            static::$all_table_and_fields = array_unique(array_merge($tables, $fields));
        }

        return static::$all_table_and_fields;
    }
}